package xipujewel.xipujewel.web.account;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.esoar.modules.utils.WebUtil;
import net.esoar.modules.web.BaseController;
import net.esoar.modules.web.pojo.JPage;
import net.esoar.modules.web.pojo.WebPojo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import xipujewel.xipujewel.entity.account.User;
import xipujewel.xipujewel.entity.app.ExchangeRate;
import xipujewel.xipujewel.entity.app.Jewel;
import xipujewel.xipujewel.entity.app.PriceBaseNumber;
import xipujewel.xipujewel.service.ExchangeRateManager;
import xipujewel.xipujewel.service.JewelManager;
import xipujewel.xipujewel.service.PriceBaseNumberManager;
import xipujewel.xipujewel.service.account.UserManager;
import xipujewel.xipujewel.utils.UserUtil;

/**
 * 
 * @author hang
 *
 */
@Controller
@RequestMapping(value = "/jewel")
public class JewelController extends BaseController<Jewel> {

	@Autowired
	private JewelManager jewelManager;

	@Autowired
	private UserManager userManager;

	@Autowired
	private ExchangeRateManager exchangeRateManager;

	@Autowired
	private PriceBaseNumberManager priceBaseNumberManager;

	@RequestMapping("")
	public String list(Model model, ServletRequest request) {
		Map<String, Object> searchParams = getFilters(request);
		initOrder("id", JPage.ASC);
		searchParams.put("EQ_isBuy", 0);

		jPage = jewelManager.search(searchParams, jPage);

		User cUser = userManager.findByLoginNameAndType01(UserUtil.getCurrentUserLoginName());
		ExchangeRate exchangeRate = exchangeRateManager.getAll().get(0);
		for (Jewel jewel : jPage.getResult()) {//重量X国际报价X折扣X汇率
			float discount2 = (float) ((100.0 + jewel.getDiscount() + cUser.getPriceBaseNumber().getJewelBaseNumBer()) / 100.0);
			float discount = (float) ((100.0 + jewel.getDiscount()) / 100.0);
			float secondPrice = jewel.getWeight() * jewel.getInternationalPrice() * (discount2)
					* exchangeRate.getRate();
			int rmbPrice = (int) (jewel.getWeight() * jewel.getInternationalPrice() * (discount) * exchangeRate
					.getRate());
			jewel.setSecondPrice(secondPrice);
			//			jewel.setDiscount2("-" + String.valueOf((1 - discount2) * 100));
			jewel.setDiscount2(String.valueOf((discount2 - 1) * 100));
			jewel.setPriceRMB(rmbPrice);
		}

		model.addAttribute("cUser", cUser);
		model.addAttribute("cdiscout", cUser.getPriceBaseNumber().getJewelBaseNumBer());
		return "jewel/jewel-list";
	}

	@RequestMapping(value = INPUT, method = RequestMethod.GET)
	public String input(@PathVariable(ID) Long id, Model model) {
		Jewel jewel = jewelManager.get(id);
		model.addAttribute("jewel", jewel);
		return "jewel/jewel-input";
	}

	@RequestMapping(value = "setDiscount", method = RequestMethod.GET)
	public String input(Model model) {
		String loginName = UserUtil.getCurrentUserLoginName();
		User user = userManager.findByLoginNameAndType01(loginName);
		PriceBaseNumber priceBaseNumber = user.getPriceBaseNumber();
		model.addAttribute("priceBaseNumber", priceBaseNumber);
		return "jewel/discount-input";
	}

	@RequestMapping(value = "companyInput", method = RequestMethod.GET)
	public String companyInput(Model model) {
		return "jewel/company-input";
	}

	@RequestMapping(value = "saveDiscount")
	@ResponseBody
	public WebPojo saveDiscount(@RequestParam("priceBaseNumberId") Long priceBaseNumberId,
			@RequestParam("discount") float discount) {
		PriceBaseNumber priceBaseNumber = priceBaseNumberManager.get(priceBaseNumberId);
		priceBaseNumber.setJewelBaseNumBer(discount);
		priceBaseNumberManager.save(priceBaseNumber);
		return WebUtil.getCloseCurrent("w_jewel");
	}

	@RequestMapping(value = SAVE, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo save(@Valid @ModelAttribute("jewel") Jewel jewel) {
		jewelManager.save(jewel);
		return WebUtil.getCloseCurrent("w_jewel");
	}

	@RequestMapping(value = DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo delete(@PathVariable(ID) Long id) {
		jewelManager.delete(id);
		return WebUtil.getNavTabAjaxDone("w_jewel");
	}

	@RequestMapping(value = "deleteByCompany", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo deleteByCompany(@RequestParam("company") String company) {
		jewelManager.deleteByCompany(company);
		return WebUtil.getCloseCurrent("w_jewel");
	}

	@RequestMapping(value = DELETES, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo deleteByIds(@RequestParam(IDS) List<Long> ids) {
		jewelManager.deletes(ids);
		return WebUtil.getNavTabAjaxDone("w_jewel");
	}

	@RequestMapping(value = "deleteAll", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public WebPojo deleteAll() {
		jewelManager.deleteAll();
		return WebUtil.getNavTabAjaxDone("w_jewel");
	}

	@RequestMapping(value = "import", method = RequestMethod.POST, produces = { "text/html" })
	@ResponseBody
	public String upload(MultipartHttpServletRequest request) {
		try {
			MultipartFile file = request.getFile("file");
			if (null == file) {
				return WebUtil.getJsonMapper().toJson(WebUtil.getError("上传文件无法识别"));
			}
			jewelManager.upload(file.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return WebUtil.getJsonMapper().toJson(WebUtil.getCloseCurrent("w_jewel"));
	}

	@RequestMapping(value = "toImport")
	public String toImport() {
		return "jewel/jewel-import";
	}

	@RequestMapping(value = "downloadJewel", method = RequestMethod.GET)
	public void downloadOrder(HttpServletRequest httpRequest, HttpServletResponse response) throws IOException {
		List<Jewel> jewels = jewelManager.getNotIsBuy();
		ExchangeRate exchangeRate = exchangeRateManager.getAll().get(0);
		response.setHeader("Content-disposition", "attachment; filename=" + new Date().getTime() + ".xlsx");
		// 确保发送的当前文本格式
		response.setContentType("application/vnd.ms-excel");
		jewelManager.getEXL(jewels, exchangeRate).write(response.getOutputStream());
		response.getOutputStream().flush();
		response.getOutputStream().close();
	}

	@Override
	public String baseMapping() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getModelName() {
		// TODO Auto-generated method stub
		return null;
	}

	@ModelAttribute("jewel")
	public Jewel getModel(@RequestParam(value = ID, required = false) Long id) {
		if (id != null) {
			return jewelManager.get(id);
		}
		return null;
	}

}
